package game.net.server;

import game.MapShareMain;

import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class Server implements Runnable{
	private Executor listenerExecutor;
	
	private boolean serverActive;
	private ServerListener listener;
	private List<ClientConnection> clients = new ArrayList<ClientConnection>();
	private ErrorLog errorLog = new ErrorLog();
	
	public static int DEFAULT_PORT = 40000; 
	
	public Server(){
		this(DEFAULT_PORT);
	}
	
	public Server(int port) {
		listenerExecutor = Executors.newCachedThreadPool();
		listenerExecutor.execute(this);
		beginListening(port);
	}

	public void beginListening(int port){
		if(listener == null)
			listener = new ServerListener(this, port, errorLog);
		listenerExecutor.execute(listener);
	}
	
//	public boolean isListening(){
//		if(listenerExecutor != null)
//			return true;
//		return false;
//	}

	@Override
	public void run() {
		serverActive = true;
		while(serverActive)
			updateClients();
	}

	private void updateClients() {
		for (ClientConnection client : clients)
			update(client);
	}

	private void update(ClientConnection client) {
		client.send(MapShareMain.game.log.getEventsSince(client.lastSentEvent));		
	}

	public void createNewConnection(Socket accept) {
		ClientConnection cc = new ClientConnection(accept);
		clients.add(cc);
	}

	public boolean isActive() {
		return serverActive;
	}

	public void shutdown() {
		serverActive = false;		
	}

	public int listeningPort() {
		return listener.listeningPort;
	}

	public ErrorLog getErrorLog() {
		return errorLog;
	}
}
